package com.tuanproject.business;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tuanproject.dao.EventsDAO;
import com.tuanproject.model.Events;

/**
 * 
 * @author TuanLe
 *
 */
@Service
public class EventsBusiness {

	@Autowired
	EventsDAO eventsDAO;

	/**
	 * get all events in database
	 * @return List<Events>
	 * @throws SQLException 
	 */
	public List<Events> getAllEvents() throws SQLException {
		List<Events> list = eventsDAO.getAllObject();
		for(Events event : list){
			String requestRaw = event.getRequestRaw();
			event.setRequestRaw(requestRaw.replaceAll("\\n", "<br/>"));
		}
		return list;
	}
	public List<Events> getEventsByTime(String fromDate, String toDate) throws SQLException {
		List<Events> events = eventsDAO.getEventsByTime(fromDate, toDate);
		return events;
	}
	

	public List<Events> getEventsFilter(String ip, String port, String method, String pattern,
			String fromDate, String toDate) throws SQLException {
		List<Events> events = eventsDAO.getEventsByTime(fromDate, toDate);
		List<Events> eventsFilter = new ArrayList<Events>();
		boolean ok = true;
		for(Events event : events){
			ok = true;
			if(!"".equals(ip.trim()) && !sourceContainIp(event.getSource(), ip)) {
				ok = false;
			} else if(!"".equals(port.trim()) && !sourceContainPort(event.getSource(), port)) {
				ok = false;
			} else if(!"".equals(method.trim()) && !compareTypeMethod(event.getRequestRaw(), method)) {
				ok = false;
			}  else if(!"".equals(pattern.trim()) && !pattern.trim().equals(event.getPattern())) {
				ok = false;
			}
			if(ok) {
				String requestRaw = event.getRequestRaw();
				event.setRequestRaw(requestRaw.replaceAll("\\n", "<br/>"));
				eventsFilter.add(event);
			}
		}
		
		return eventsFilter;
	}
	
	private boolean sourceContainIp(String source, String ip) {
		boolean result = false;
		String[] socket = source.split(":");
		if(socket.length > 0 && socket[0].equals(ip)) {
			result = true;
		}
		return result;
	}
	
	private boolean sourceContainPort(String source, String port) {
		boolean result = false;
		String[] socket = source.split(":");
		if(socket.length > 1 && socket[1].equals(port)) {
			result = true;
		}
		return result;
	}
	
	private boolean compareTypeMethod(String requestRaw, String method) {
		boolean result = false;
		String[] methods = requestRaw.split("\\n");
		String[] methodTemp = methods[0].split("/");
		if(methodTemp.length > 0 && methodTemp[0].trim().equals(method)) {
			result = true;
		}
		return result;
	}
	
}
